package com.trace.demo.controller;

import com.trace.demo.entity.*;
import com.trace.demo.repository.*;
import com.trace.demo.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/api/trace-info")
public class TraceCodeController {

    @Autowired
    private TraceCodeRepository traceCodeRepository;
    
    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private FarmingInfoRepository farmingInfoRepository;

    @Autowired
    private DistributionInfoRepository distributionInfoRepository;

    @Autowired
    private OrderRepository orderRepository;

    @GetMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> getAllTraceCodes(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        int offset = (page - 1) * size;
        
        // 获取溯源码并添加分页信息
        List<TraceCode> traceCodes = traceCodeRepository.findAll();
        List<TraceCode> pagedTraceCodes;
        
        if (offset >= traceCodes.size()) {
            pagedTraceCodes = new ArrayList<>();
        } else {
            int endIndex = Math.min(offset + size, traceCodes.size());
            pagedTraceCodes = traceCodes.subList(offset, endIndex);
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("traceCodes", pagedTraceCodes);
        response.put("total", traceCodes.size());
        response.put("page", page);
        response.put("size", size);
        
        return ResponseEntity.ok(new ApiResponse<>(true, "Trace codes retrieved successfully", response));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getTraceCodeById(@PathVariable Long id) {
        Optional<TraceCode> traceCodeOpt = traceCodeRepository.findById(id);
        if (!traceCodeOpt.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Trace code not found with id: " + id, null));
        }
        
        TraceCode traceCode = traceCodeOpt.get();
        
        // 生成二维码URL（这里用一个模拟的URL）
        String qrCodeUrl = "https://example.com/qr/" + traceCode.getCode();
        
        Map<String, Object> response = new HashMap<>();
        response.put("traceCode", traceCode);
        response.put("qrCodeUrl", qrCodeUrl);
        
        return ResponseEntity.ok(new ApiResponse<>(true, "Trace code retrieved successfully", response));
    }

    @GetMapping("/code/{code}")
    public ResponseEntity<ApiResponse<TraceCode>> getTraceCodeByCode(@PathVariable String code) {
        Optional<TraceCode> traceCode = traceCodeRepository.findByCode(code);
        return traceCode.map(value -> ResponseEntity.ok(new ApiResponse<>(true, "Trace code retrieved successfully", value)))
                .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "Trace code not found with code: " + code, null)));
    }

    @PostMapping("/generate")
    public ResponseEntity<ApiResponse<Map<String, Object>>> generateTraceCode(@RequestBody Map<String, Object> requestData) {
        // 从请求中获取数据
        Long productId = Long.valueOf(requestData.get("productId").toString());
        String batchNumber = (String) requestData.get("batchNumber");
        int quantity = Integer.parseInt(requestData.get("quantity").toString());
        
        // 验证产品是否存在
        Optional<Product> productOpt = productRepository.findById(productId);
        if (!productOpt.isPresent()) {
            return ResponseEntity.badRequest()
                    .body(new ApiResponse<>(false, "Product not found with id: " + productId, null));
        }
        
        // 验证数量是否合理
        if (quantity < 1 || quantity > 100) {
            return ResponseEntity.badRequest()
                    .body(new ApiResponse<>(false, "Quantity must be between 1 and 100", null));
        }
        
        List<TraceCode> generatedCodes = new ArrayList<>();
        
        // 生成指定数量的溯源码
        for (int i = 0; i < quantity; i++) {
            TraceCode traceCode = new TraceCode();
            String generatedCode = UUID.randomUUID().toString().replace("-", "").substring(0, 16).toUpperCase();
            traceCode.setCode(generatedCode);
            traceCode.setBatchId(batchNumber);
            traceCode.setProductId(productId);
            traceCode.setBatchNumber(batchNumber);
            traceCode.setStatus(1); // 设置状态为有效
            traceCode.setCreatedAt(new Date());
            
            TraceCode savedTraceCode = traceCodeRepository.save(traceCode);
            generatedCodes.add(savedTraceCode);
        }
        
        // 更新产品的批次号（如果需要）
        Product product = productOpt.get();
        if (product.getBatchNumber() == null || product.getBatchNumber().isEmpty()) {
            product.setBatchNumber(batchNumber);
            productRepository.save(product);
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("generatedCodes", generatedCodes);
        response.put("count", generatedCodes.size());
        
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(new ApiResponse<>(true, "Trace codes generated successfully", response));
    }
    
    @GetMapping("/{id}/download")
    public ResponseEntity<ApiResponse<Map<String, Object>>> downloadTraceInfo(@PathVariable Long id) {
        Optional<TraceCode> traceCodeOpt = traceCodeRepository.findById(id);
        if (!traceCodeOpt.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Trace code not found with id: " + id, null));
        }
        
        TraceCode traceCode = traceCodeOpt.get();
        
        // 生成下载URL（这里用一个模拟的URL）
        String downloadUrl = "https://example.com/download/" + traceCode.getCode();
        
        Map<String, Object> response = new HashMap<>();
        response.put("downloadUrl", downloadUrl);
        
        return ResponseEntity.ok(new ApiResponse<>(true, "Trace code download URL generated successfully", response));
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteTraceInfo(@PathVariable Long id) {
        Optional<TraceCode> traceCodeOpt = traceCodeRepository.findById(id);
        if (!traceCodeOpt.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Trace code not found with id: " + id, null));
        }
        
        traceCodeRepository.deleteById(id);
        
        return ResponseEntity.ok(new ApiResponse<>(true, "Trace code deleted successfully", null));
    }

    @GetMapping("/count")
    public ResponseEntity<ApiResponse<Long>> countTraceCodes() {
        Long count = traceCodeRepository.count();
        return ResponseEntity.ok(new ApiResponse<>(true, "Trace codes count retrieved successfully", count));
    }

    @GetMapping("/count/today")
    public ResponseEntity<ApiResponse<Long>> countTodayNewTraceCodes() {
        LocalDateTime startOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT);
        // Convert LocalDateTime to Date for the repository method
        Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
        Long count = traceCodeRepository.countByCreatedAtAfter(startDate);
        return ResponseEntity.ok(new ApiResponse<>(true, "Today's new trace codes count retrieved successfully", count));
    }

    // 追溯信息查询接口，返回完整的追溯信息（种植信息和流通信息）
    @GetMapping("/query/{code}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> queryTraceInfo(@PathVariable String code) {
        System.out.println("查询的code是"+code);
        Optional<TraceCode> traceCodeOptional = traceCodeRepository.findByCode(code);
        if (traceCodeOptional.isEmpty()) {
            System.out.println("不存在            "+code);
            // 尝试使用 findByCodeOrTraceCode 方法
            traceCodeOptional = traceCodeRepository.findByCodeOrTraceCode(code, code);
            if (!traceCodeOptional.isPresent()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
//                        .body(new ApiResponse<>(false, "Trace code not found with code: " + code, null));
                        .body(new ApiResponse<>(false, "当前溯源码不存在", null));

            }
        }

        TraceCode traceCode = traceCodeOptional.get();
        String batchId = traceCode.getBatchId();
        Long productId = traceCode.getProductId();
        Integer times = traceCode.getFrequency();

        Order order = orderRepository.findByProductId(productId);

        Map<String, Object> orders = new HashMap<>();

        orders.put("sales",order.getSales());
        orders.put("customerName",order.getCustomerName());
        orders.put("customerPhone",order.getCustomerPhone());
        orders.put("location",order.getLocation());


        // 创建结果映射
        Map<String, Object> traceInfo = new HashMap<>();
        traceInfo.put("traceCode", traceCode);
        String farmName="";
        // 获取产品信息
        Optional<Product> productOptional = productRepository.findById(traceCode.getProductId());
        if (productOptional.isPresent()) {
            Product product = productOptional.get();
            farmName= product.getFarmer().getFarmName();
            // 添加完整的产品信息
            traceInfo.put("productName", product.getProductName());
            traceInfo.put("productCode", product.getProductCode());
            
            // 确保批次号不为空
            String batchNumber = product.getBatchNumber();
            if (batchNumber == null || batchNumber.isEmpty()) {
                // 如果产品的批次号为空，则使用溯源码的批次号
                batchNumber = traceCode.getBatchNumber();
                // 如果溯源码的批次号也为空，则使用批次ID
                if (batchNumber == null || batchNumber.isEmpty()) {
                    batchNumber = batchId;
                }
            }


            HashMap<String, Object> products = new HashMap<>();
            products.put("productName",product.getProductName());
            products.put("batchNumber", product.getBatchNumber());
            products.put("storageMethods",product.getStorageMethods());
            products.put("productionStandard",product.getProductionStandard());
            products.put("plantingDate",product.getPlantingDate());

            traceInfo.put("products", products);
            traceInfo.put("batchNumber", batchNumber);
            traceInfo.put("productImage", product.getProductImage());
            traceInfo.put("description", product.getDescription());
            traceInfo.put("category", product.getCategory());
            traceInfo.put("specification", product.getSpecification());

            // 获取产地信息 - 优先使用产品自身的origin字段
            String origin = "";
            if (product.getOrigin() != null && !product.getOrigin().isEmpty()) {
                origin = product.getOrigin();
            } else if (product.getFarmer() != null) {
                // 如果产品没有origin字段，则从Farmer实体获取
                if (product.getFarmer().getProvince() != null && !product.getFarmer().getProvince().isEmpty()) {
                    origin += product.getFarmer().getProvince();
                }
                if (product.getFarmer().getCity() != null && !product.getFarmer().getCity().isEmpty()) {
                    origin += " " + product.getFarmer().getCity();
                }
                // 如果获取到了产地信息，更新产品的origin字段
                if (!origin.isEmpty()) {
                    product.setOrigin(origin);
                    productRepository.save(product);
                }
            }
            
            // 如果从产品或农户获取不到产地信息，尝试从种植信息获取
            if (origin.isEmpty()) {
                Optional<FarmingInfo> farmingInfoOpt = farmingInfoRepository.findByBatchId(batchId);
                if (farmingInfoOpt.isPresent() && farmingInfoOpt.get().getLocation() != null) {
                    origin = farmingInfoOpt.get().getLocation();
                    // 更新产品的origin字段
                    product.setOrigin(origin);
                    productRepository.save(product);
                }
            }
            
            traceInfo.put("origin", origin);

            // 添加质量等级和生产标准 - 优先使用产品中存储的值
            traceInfo.put("qualityLevel", product.getQualityLevel() != null ? product.getQualityLevel() : "特级");
            traceInfo.put("productionStandard", product.getProductionStandard() != null ? product.getProductionStandard() : "GB/T 19330-2013");
            traceInfo.put("verified", true);  // 是否已验证，目前数据库中没有对应字段
        }

        // 查询与该批次ID关联的种植信息
        Optional<FarmingInfo> farmingInfoOptional = farmingInfoRepository.findByBatchId(batchId);
        if (farmingInfoOptional.isPresent()) {
            FarmingInfo farmingInfo = farmingInfoOptional.get();
            traceInfo.put("farmingInfo", farmingInfo);

            // 添加格式化的种植信息
            Map<String, Object> formattedFarmingInfo = new HashMap<>();

            // 从数据库实体中获取种植信息
//            formattedFarmingInfo.put("farmer", farmingInfo.getUser() != null ? farmingInfo.getUser().getUsername() : "");
            formattedFarmingInfo.put("farmer",farmName);
            formattedFarmingInfo.put("region", farmingInfo.getLocation());
            formattedFarmingInfo.put("environment", farmingInfo.getWeather() + "，" + farmingInfo.getSoil());
            formattedFarmingInfo.put("farmingMethod", farmingInfo.getDescription());
            formattedFarmingInfo.put("waterSource", "天然水源");  // FarmingInfo 中没有 waterSource 字段
            formattedFarmingInfo.put("soilType", farmingInfo.getSoil());
            formattedFarmingInfo.put("fertilizer", farmingInfo.getFertilizer());
            formattedFarmingInfo.put("pesticide", farmingInfo.getPesticide());

            traceInfo.put("farmingDetails", formattedFarmingInfo);
        } else {
            traceInfo.put("farmingInfo", new HashMap<>());
        }

        // 查询与该批次ID关联的流通信息

        Optional<DistributionInfo> distributionInfoList = distributionInfoRepository.findById(order.getId());
        HashMap<String, Object> distributionInfos = new HashMap<>();
        if(distributionInfoList.isPresent()) {

            DistributionInfo distributionInfo = distributionInfoList.get();

            distributionInfos.put("logisticsCompany",distributionInfo.getLogisticsCompany());
            distributionInfos.put("logisticsNumber",distributionInfo.getLogisticsNumber());
            distributionInfos.put("shipDate",distributionInfo.getShipDate());
            distributionInfos.put("startLocation",distributionInfo.getStartLocation());
            distributionInfos.put("toLocation",distributionInfo.getToLocation());



            traceInfo.put("distributionInfo", distributionInfos);
        }




//        List<DistributionInfo> distributionInfoList = distributionInfoRepository.findByBatchId(batchId);
//
//        if (!distributionInfoList.isEmpty()) {
//            traceInfo.put("distributionInfo", distributionInfoList);
//
//            // 创建溯源步骤信息
//            List<Map<String, Object>> steps = new ArrayList<>();
//
//            // 从种植信息中添加种植步骤
//            if (farmingInfoOptional.isPresent()) {
//                FarmingInfo farmingInfo = farmingInfoOptional.get();
//                Map<String, Object> plantingStep = new HashMap<>();
//                plantingStep.put("title", "种植");
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//                plantingStep.put("time", farmingInfo.getPlantingDate() != null ?
//                        farmingInfo.getPlantingDate().format(formatter) : "");
//                plantingStep.put("description", "在" + farmingInfo.getLocation() + "种植");
//                steps.add(plantingStep);
//
//                // 如果存在收获日期，添加采收步骤
//                if (farmingInfo.getHarvestDate() != null) {
//                    Map<String, Object> harvestStep = new HashMap<>();
//                    harvestStep.put("title", "采收");
//                    harvestStep.put("time", farmingInfo.getHarvestDate().format(formatter));
//                    harvestStep.put("description", "产品采收");
//                    steps.add(harvestStep);
//                }
//            }
//
//            // 从流通信息中创建流通步骤
//            for (DistributionInfo info : distributionInfoList) {
//                Map<String, Object> step = new HashMap<>();
//
//                // 确定步骤标题 - 所有流通信息都表示为"流通"步骤
//                step.put("title", "流通");
//
//                // 添加步骤详情
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//                step.put("time", info.getDistributionDate() != null ?
//                        info.getDistributionDate().format(formatter) : "");
//                step.put("description", info.getNotes() != null ? info.getNotes() :
//                        "从" + info.getFromLocation() + "到" + info.getToLocation());
//                steps.add(step);
//            }
//
//            traceInfo.put("steps", steps);
//        } else {
//            // 如果没有流通信息，至少添加从种植信息中获取的步骤
//            List<Map<String, Object>> steps = new ArrayList<>();
//
//            if (farmingInfoOptional.isPresent()) {
//                FarmingInfo farmingInfo = farmingInfoOptional.get();
//
//                // 种植步骤
//                Map<String, Object> plantingStep = new HashMap<>();
//                plantingStep.put("title", "种植");
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//                plantingStep.put("time", farmingInfo.getPlantingDate() != null ?
//                        farmingInfo.getPlantingDate().format(formatter) : "");
//                plantingStep.put("description", "在" + farmingInfo.getLocation() + "种植");
//                steps.add(plantingStep);
//
//                // 如果存在收获日期，添加采收步骤
//                if (farmingInfo.getHarvestDate() != null) {
//                    Map<String, Object> harvestStep = new HashMap<>();
//                    harvestStep.put("title", "采收");
//                    harvestStep.put("time", farmingInfo.getHarvestDate().format(formatter));
//                    harvestStep.put("description", "产品采收");
//                    steps.add(harvestStep);
//                }
//            }
//
//            if (!steps.isEmpty()) {
//                traceInfo.put("steps", steps);
//            } else {
//                traceInfo.put("distributionInfo", new HashMap<>());
//            }
//        }
        traceInfo.put("orders",orders);
        if (times == null) {
            times = 0;
        }
        if (times == 0) {
            traceInfo.put("frequency", "当前溯源码为首次查询");
        } else {
            String value = String.format("当前溯源码查询次数为%s", times);
            traceInfo.put("frequency", value);
        }
        try {
            traceCodeRepository.updateFrequencyByCode(code);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return ResponseEntity.ok(new ApiResponse<>(true, "Trace information retrieved successfully", traceInfo));
    }
}
